//
//  YLCSendVideoNextViewController.m
//  LinYa
//
//  Created by 初程程 on 2018/5/1.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCSendVideoNextViewController.h"
#import <AVFoundation/AVAsset.h>
#import <AssetsLibrary/AssetsLibrary.h>
@interface YLCSendVideoNextViewController ()

@end

@implementation YLCSendVideoNextViewController
{
    UITextField *titleField;
    UIImageView *lineView;
    UIImageView *firstVideoView;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (UIBarButtonItem *)leftBarButtonItem{
    
    return [YLCFactory createTitleBarButtonItemWithTitle:@"取消" titleColor:[UIColor whiteColor] selector:@selector(gotoCancel) target:self];
}
- (UIBarButtonItem *)rightBarButtonItem{
    
    return [YLCFactory createTitleBarButtonItemWithTitle:@"完成" titleColor:[UIColor whiteColor] selector:@selector(gotoFinish) target:self];
}
- (void)gotoCancel{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)gotoFinish{
    [self uploadVideo];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createCustomView];
}
- (void)createCustomView{
    titleField = [YLCFactory createFieldWithPlaceholder:@"标题(最多30个字)"];
    
    [self.view addSubview:titleField];
    
    lineView = [[UIImageView alloc] init];
    
    [self.view addSubview:lineView];
    
    firstVideoView = [[UIImageView alloc] init];
    firstVideoView.backgroundColor = [UIColor redColor];
    UIImage *image = [self thumbnailImageForVideo:_videoPath atTime:1];
    firstVideoView.image = image;
    [self.view addSubview:firstVideoView];
    WS(weakSelf)
    [titleField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left);
        make.top.equalTo(weakSelf.view.mas_top);
        make.width.equalTo(weakSelf.view.frameWidth);
        make.height.equalTo(40);
    }];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left);
        make.right.equalTo(weakSelf.view.mas_right);
        make.top.equalTo(titleField.mas_bottom).offset(5);
        make.height.equalTo(0.5);
    }];
    
    [firstVideoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleField.mas_left).offset(20);
        make.top.equalTo(lineView.mas_bottom).offset(20);
        make.width.height.equalTo(80);
    }];
}
- (void)uploadVideo{
    if (JK_IS_STR_NIL(titleField.text)) {
        [SVProgressHUD showErrorWithStatus:@"请输入标题"];
        return;
    }

    NSData *videoData = [NSData dataWithContentsOfURL:_videoPath];

    if (_isAlbum) {
        videoData = _albumVideoData;
    }
    
    NSString *baseString = [videoData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    NSString *videoString = [NSString stringWithFormat:@"data:video/mp4;base64,%@",baseString];
    
    YLCAccountModel *model = [[YLCAccountManager shareManager] currentAccount];
    
    NSString *path = @"";
    NSDictionary *param = @{};
    if (_isEasy) {
        path = @"app/sygt/uploadVideo";
        param = @{@"videoData":videoString,@"token":model.token,@"userId":model.user_id,@"title":titleField.text,@"classifyId":_classifyId};
    }else{
        path = @"app/videoLife/publish";
        param = @{@"videoData":videoString,@"token":model.token,@"userId":model.user_id,@"title":titleField.text,@"type":@"趣事"};
    }
    
    [YLCNetWorking loadNetServiceWithParam:param method:@"POST" urlPath:path delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            NSLog(@"上传失败");
            return ;
        }
        [SVProgressHUD showSuccessWithStatus:@"上传成功"];
        if (_isEasy) {
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        
    }];
}
- (UIImage*) thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
    
    if(!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
    
    UIImage*thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage: thumbnailImageRef] : nil;
    
    return thumbnailImage;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
